package com.habdqn.studentmanager.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.habdqn.studentmanager.bean.ajax.Response;
import com.habdqn.studentmanager.constant.ErrorCode;
import com.habdqn.studentmanager.exception.StudentException;
import com.habdqn.studentmanager.util.ConfigUtil;
import com.habdqn.studentmanager.util.FileUtil;
import com.habdqn.studentmanager.util.ProjectUtil;
import com.habdqn.studentmanager.util.UUIDUtil;

/**
 * @author Administrator
 * 
 *         2017年5月20日
 * 
 */
@Controller
public class UploadController {

    private static Logger logger = Logger.getLogger(UploadController.class);

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Response upload(@RequestParam("file") CommonsMultipartFile file) {
        Response rsp = new Response();

        String suffix = FileUtil.getSuffix(file);
        String fileName = UUIDUtil.getUUID() + "." + suffix;
        String path = ProjectUtil.getRealPath() + ConfigUtil.getKey("uploadPath");

        try {
            FileUtil.move(file, path, fileName);
        }
        catch (StudentException e) {
            logger.error("上传文件失败", e);
            rsp.setErr(ErrorCode.System_Error);
            rsp.setMsg(e.getMessage());
        }
        rsp.setMsg(fileName);
        return rsp;
    }
}
